package basic;

import java.util.HashSet;
import java.util.Set;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;


public class SouGou3 {

	/**修改版啊！！！搜狗第三题
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
		if(args.length!=2){
			System.err.println("User path err!!");
			System.exit(-1);
		}
		Job job = new Job(new Configuration(),"sougou");
		job.setJarByClass(SouGou3.class);
		
		FileInputFormat.addInputPath(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job,new Path(args[1]));
		
		job.setMapperClass(smap.class);
		job.setReducerClass(soreduce.class);
		
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(Text.class);
		
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(NullWritable.class);
		
		job.waitForCompletion(true);

	}
	public static class smap extends Mapper<LongWritable,Text, Text,Text>{
		protected void map(LongWritable key, Text value, org.apache.hadoop.mapreduce.Mapper<LongWritable,Text,Text,Text>.Context context) throws java.io.IOException ,InterruptedException {
			String[] lines = value.toString().split("\t");
			if (lines.length == 6 && lines[2].trim().contains("百度")) {
				String uid = lines[1].trim();
				String keyword=lines[2].trim();
				context.write(new Text(uid),new Text(keyword));// map输出的中间结果是：《百度外卖》
			}
		};
	}
	public static class soreduce extends Reducer<Text,Text,Text, NullWritable>{
		Set<String> sets = new HashSet<String>();
		Set<String> sets2 = new HashSet<String>();
		//k2
		protected void reduce(Text k2, java.lang.Iterable<Text> values, org.apache.hadoop.mapreduce.Reducer<Text,Text,Text,NullWritable>.Context context) throws java.io.IOException ,InterruptedException {
			sets.add(k2.toString());
			for (Text text : values) {
				if(values.toString().contains("百度影音")){
					sets2.add(values.toString());
				}
			}
		};
		protected void cleanup(org.apache.hadoop.mapreduce.Reducer<Text,Text,Text,NullWritable>.Context context) throws java.io.IOException ,InterruptedException {
			double x=sets.size();
			double y=sets2.size();
			double z=y/x;
			context.write(new Text("结果可能是这:"+ y), NullWritable.get());
		};
	}

}
